/**
 *  @file SDLFriendlyShip.cpp
 *
 *  @date 24-nov-2009
 *  @author Ives van der Flaas
 */

#include "multistateRepresentation.h"
#include "SDLFriendlyShip.h"
#include "SDLBullet.h"
#include "SDLImageRepresentation.h"
#include "SDLKeyboardController.h"
#include "SDLAudioManager.h"
#include "SDLScoreKeeper.h"

namespace si_sdl
{

SDLFriendlyShip::SDLFriendlyShip():
	FriendlyShip()
{
	si::MultistateRepresentation* msRep = new si::MultistateRepresentation();

	fCenter = msRep->addState(std::tr1::shared_ptr<si::StaticRepresentation>(
			new SDLImageRepresentation("images/friendlyshipcenter.png")));
	fLeft = msRep->addState(std::tr1::shared_ptr<si::StaticRepresentation>(
				new SDLImageRepresentation("images/friendlyshipleft.png")));
	fRight = msRep->addState(std::tr1::shared_ptr<si::StaticRepresentation>(
				new SDLImageRepresentation("images/friendlyshipright.png")));

	msRep->changeState(fCenter);

	fRepresentation = std::tr1::shared_ptr<si::Representation>(msRep);


	fController = std::tr1::shared_ptr<si::Controller>(
						new SDLKeyboardController(fStartPosition, fVirtualSize));

	fScoreKeeper = std::tr1::shared_ptr<si::ScoreKeeper>(
						new SDLScoreKeeper());
}

SDLFriendlyShip::~SDLFriendlyShip()
{
}
std::tr1::shared_ptr<si::Projectile> SDLFriendlyShip::newBullet()
{
	return std::tr1::shared_ptr<si::Projectile>(
									new SDLBullet(
											si::Vector2(
													fController->getPosition().getX() + fVirtualSize.getX()/2,
													fController->getPosition().getY()),
													si::DIR_UP));
}

void SDLFriendlyShip::update(double time)
{

	FriendlyShip::update(time);

	Uint8 *keystates = SDL_GetKeyState(0);

	double firingRate = 0.6;

	// only fire when space bar is pressed and more than 0.4 seconds have passed.
	if((shotTimer.poll() > firingRate) && (keystates[SDLK_SPACE]))
	{
		fire();
		shotTimer.reset();
	}

	//change the state of rep according to movement
	if(std::tr1::dynamic_pointer_cast<SDLKeyboardController>(fController)->goingLeft())
		std::tr1::dynamic_pointer_cast<si::MultistateRepresentation>(fRepresentation)->changeState(fLeft);
	else if(std::tr1::dynamic_pointer_cast<SDLKeyboardController>(fController)->goingRight())
		std::tr1::dynamic_pointer_cast<si::MultistateRepresentation>(fRepresentation)->changeState(fRight);
	else
		std::tr1::dynamic_pointer_cast<si::MultistateRepresentation>(fRepresentation)->changeState(fCenter);
}

void SDLFriendlyShip::takeHit(int hitAmount)
{
	FriendlyShip::takeHit(hitAmount);

	SDLAudioManager::get().playSound("audio/friendlyhit.wav", PLAYONCE);
}
void SDLFriendlyShip::fire()
{
	FriendlyShip::fire();

	SDLAudioManager::get().playSound("audio/gun.wav", PLAYONCE);
}
}
